package com.itzhoun.controller;

import com.itzhoun.client.ForestSimpleClient;
import com.itzhoun.client.UploadFileClient;
import com.itzhoun.response.ApiResultResponse;
import com.itzhoun.response.User;
import com.itzhoun.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author 周楠
 * @Date 2022/07/05/下午 10:15
 */
@Slf4j
@RestController
@Api(tags = "Forest测试类")
public class ForestSimpleController {

    @Resource
    private ForestSimpleClient forestSimpleClient;

    @Resource
    private UploadFileClient uploadFileClient;


    @GetMapping("/getName")
    @ApiOperation(value = "forest带参get请求")
    public String getForestName(@RequestParam(required = false) String name){
        return "hello" + name;
    }

    @GetMapping("/helloForest")
    @ApiOperation(value = "forest无参get请求")
    public String helloForest(){
        return "hello,Forest";
    }

    @GetMapping("/getNameApi")
    @ApiOperation(value = "forest有参get请求并且返回响应体")
    public ApiResultResponse<String> getNameApi(@RequestParam(required = false) String name){
        return ApiResultResponse.ok(name);
    }

    @PostMapping("/postJson")
    @ApiOperation(value = "forest发送json自定义响应体")
    public ApiResultResponse<User> postJson(@RequestBody @Validated User user){
        return ApiResultResponse.ok(user);
    }

    @ApiOperation(value = "上传", notes = "上传", consumes = "multipart/form-data")
    @PostMapping("/uploadFile")
    public ApiResultResponse<String> uploadFile(@RequestPart MultipartFile file){
        return ApiResultResponse.ok(uploadFileClient.uploadFile(file));
    }

    @ApiOperation("下载文件")
    @GetMapping("/downloadFile")
    public void downloadFile(@ApiParam("文件地址") @RequestParam String fileUrl, HttpServletResponse response){
        InputStream inputStream = uploadFileClient.downloadFile(fileUrl);
        //这里主要是做支持下载操作的
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(fileUrl.getBytes(), StandardCharsets.ISO_8859_1));
        FileUtils.writeFile(response,inputStream);
    }


}
